package com.dnjn.happiness.emo.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.config.DateTimeFormatHolder;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.bean.BeanUtils;
import com.dnjn.happiness.common.core.utils.poi.ExcelUtil;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.InnerAuth;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.emo.api.domain.EmoAvgScoreDaily;
import com.dnjn.happiness.emo.domain.vo.AvgScoreChangeBean;
import com.dnjn.happiness.emo.domain.vo.EmoAvgScoreDailyVO;
import com.dnjn.happiness.emo.handler.ComputeHappinessScore;
import com.dnjn.happiness.emo.service.IEmoAvgScoreDailyService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

/**
 * 快乐值日均Controller
 *
 * @author happiness
 * @date 2024-02-27
 */
@Tag(name = "score admin daily 快乐值日均", description = "快乐值日均")
@RestController
@RequestMapping("/admin/score/daily")
public class AdminEmoAvgScoreDailyController extends BaseController {
    @Autowired
    private IEmoAvgScoreDailyService emoAvgScoreDailyService;


    @InnerAuth
    @GetMapping("/updateDaily/{userId}/{happinessScores}/{time}")
    public void updateDaily(@PathVariable Long userId,@PathVariable Integer happinessScores,@PathVariable String time) {
        time = time.substring(0, 10);
        BigDecimal score = BigDecimal.valueOf(happinessScores);
        EmoAvgScoreDaily one = emoAvgScoreDailyService.lambdaQuery().eq(EmoAvgScoreDaily::getCurrDate, time).eq(EmoAvgScoreDaily::getUserId, userId).eq(EmoAvgScoreDaily::getDeleted, '0').one();
        if (ObjectUtil.isNotNull(one)) {
            one.setScoreAvg(score);
        } else {
            one = new EmoAvgScoreDaily().setCurrDate(LocalDate.parse(time, DateTimeFormatHolder.FORMATTER_YYYY_MM_DD)).setUserId(userId).setScoreAvg(score);
        }
        emoAvgScoreDailyService.saveOrUpdate(one);
    }

    @InnerAuth
    @GetMapping("/getEmoAvgScoreDailyByUserIdAndDate")
    public R<EmoAvgScoreDaily> getEmoAvgScoreDailyByUserIdAndDate(@RequestParam Long userId, @RequestParam LocalDate localDate){
        return R.ok(emoAvgScoreDailyService.lambdaQuery().eq(EmoAvgScoreDaily::getUserId, userId).eq(EmoAvgScoreDaily::getCurrDate, localDate).one());
    }

    /**
     * 查询快乐值日均列表
     */
    @RequiresPermissions("@ss.hasPermi('score:daily:list')")
    @PostMapping("/list")
    @Log(title = "biz", businessType = BusinessType.LIST)
    public AjaxResult list(@RequestBody EmoAvgScoreDailyVO vo, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        EmoAvgScoreDaily emoAvgScoreDaily = new EmoAvgScoreDaily();
        BeanUtils.copyPropsIgnoreNull(vo, emoAvgScoreDaily);
        Page page = Page.of(current, size);
        Page<EmoAvgScoreDaily> list = emoAvgScoreDailyService.page(page, Wrappers.query(emoAvgScoreDaily));
        return success(list);
    }

    /**
     * 导出快乐值日均列表
     */
    @Log(title = "快乐值日均", businessType = BusinessType.EXPORT)
    @RequiresPermissions("@ss.hasPermi('score:daily:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, EmoAvgScoreDailyVO vo) {
        EmoAvgScoreDaily emoAvgScoreDaily = new EmoAvgScoreDaily();
        BeanUtils.copyPropsIgnoreNull(vo, emoAvgScoreDaily);

        List<EmoAvgScoreDaily> list = emoAvgScoreDailyService.list(Wrappers.query(emoAvgScoreDaily));
        ExcelUtil<EmoAvgScoreDaily> util = new ExcelUtil<EmoAvgScoreDaily>(EmoAvgScoreDaily.class);
        util.exportExcel(response, list, "快乐值日均数据");
    }

    /**
     * 获取快乐值日均详细信息
     */
    @RequiresPermissions("@ss.hasPermi('score:daily:query')")
    @GetMapping(value = "/{id}")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult get(@PathVariable("id") Long id) {
        return success(emoAvgScoreDailyService.getById(id));
    }

    /**
     * 新增快乐值日均
     */
    @Log(title = "快乐值日均", businessType = BusinessType.INSERT)
    @RequiresPermissions("@ss.hasPermi('score:daily:add')")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody EmoAvgScoreDailyVO vo) {
        EmoAvgScoreDaily emoAvgScoreDaily = new EmoAvgScoreDaily();
        BeanUtils.copyPropsIgnoreNull(vo, emoAvgScoreDaily);

        emoAvgScoreDaily.setCreateBy(SecurityUtils.getUsername());
        return toAjax(emoAvgScoreDailyService.save(emoAvgScoreDaily));
    }

    /**
     * 修改快乐值日均
     */
    @Log(title = "快乐值日均", businessType = BusinessType.UPDATE)
    @RequiresPermissions("@ss.hasPermi('score:daily:edit')")
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody EmoAvgScoreDailyVO vo) {
        EmoAvgScoreDaily emoAvgScoreDaily = new EmoAvgScoreDaily();
        BeanUtils.copyPropsIgnoreNull(vo, emoAvgScoreDaily);
        return toAjax(emoAvgScoreDailyService.updateById(emoAvgScoreDaily));
    }

    /**
     * 删除快乐值日均
     */
    @Log(title = "快乐值日均", businessType = BusinessType.DELETE)
    @RequiresPermissions("@ss.hasPermi('score:daily:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(emoAvgScoreDailyService.removeBatchByIds(Arrays.asList(ids)));
    }


    /**
     * 统计分析 - 周日历 周对比
     */
    public AjaxResult weeklycalendar() {
        LocalDate now = LocalDate.now();
        return success();
    }

    @Autowired
    private ComputeHappinessScore computeHappinessScore;

    /**
     * 计算当日日均
     */
    @GetMapping("/computeTodayAvgScore")
    public AjaxResult computeTodayAvgScore() {
        computeHappinessScore.computeDailyAvgScore();
        return success();
    }

    /**
     * 根据weekofyear计算周均
     */
    @GetMapping("/computeWeekAvgScoreByWeekOfYear/{weekOfYear}")
    public AjaxResult computeWeekAvgScoreByWeekOfYear(@PathVariable String weekOfYear) {
        computeHappinessScore.computeWeekAvgScoreByWeekOfYear(weekOfYear);
        return success();
    }

    /**
     * 根据用户id查询近一个月的分支变化
     */
    @GetMapping("/getScoreChangeByUserId/{userId}")
    public AjaxResult getScoreChangeByUserId(@PathVariable Long userId) {
        Assert.notNull(userId, "userId不能为空");
        List<AvgScoreChangeBean> list = emoAvgScoreDailyService.getScoreChangeByUserId(userId);
        return success(list);
    }


}
